package io.acm.modules.app.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.acm.common.exception.acmException;
import io.acm.common.utils.ConfigConstant;
import io.acm.common.utils.HttpRequest;
import io.acm.common.utils.R;
import io.acm.common.utils.RR;
import io.acm.modules.admin.entity.SystemEntity;
import io.acm.modules.admin.service.SystemService;
import io.acm.modules.app.entity.CompetitionEntity;
import io.acm.modules.app.entity.StudentEntity;
import io.acm.modules.app.service.CompetionServer;
import io.acm.modules.app.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@RestController
@RequestMapping("/app/competition")
@Api(tags = "APP登录接口")
public class AppCompetitionController {

    @Autowired
    private CompetionServer competionServer;

    @Autowired
    private  StudentService studentService;

    @Autowired
    private SystemService systemService;

    @GetMapping("/list/{id}")
    @ApiOperation("获取某个比赛信息")
    public R studentInfo(@PathVariable("id") String id) {
        CompetitionEntity response = competionServer.getById(id);
        System.out.println("!!!!!-----!!!!!！！");
        System.out.println(response);
        return R.ok().put("result", response);
    }


    @ApiOperation("保存比赛信息")
    @PostMapping("/save")
    public R save(@RequestBody CompetitionEntity competition){
        competionServer.save(competition);
        return R.ok();
    }

    @ApiOperation("删除比赛信息")
    @PostMapping("/remove")
    public R remove(@RequestBody int id){
        competionServer.removeById(id);
        return R.ok();
    }

    @ApiOperation("获取比赛名称")
    @GetMapping("/getracelist")
    public R GetRace(){

       LambdaQueryWrapper<CompetitionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompetitionEntity::getMark,1);
        List<CompetitionEntity> list = competionServer.list(wrapper);
        List<String> raceList = new ArrayList<>();

        for (CompetitionEntity entity : list) {
            raceList.add(entity.getName());
        }
        return R.ok().put("data",raceList);
    }

    @ApiOperation("根据比赛名字获取报名人信息")
    @GetMapping("/getbyname")
    public R GetByName(@RequestParam("name") String name){//@PathVariable("name") String name){
        String decodedRacename = "";
        try {
            decodedRacename = URLDecoder.decode(name, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        LambdaQueryWrapper<StudentEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentEntity::getRaceName,decodedRacename);

        List<StudentEntity> list = studentService.list(wrapper);
        return R.ok().put("list",list);
    }

    @ApiOperation("根据id删除报名人的")
    @PostMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        studentService.removeByIds(Arrays.asList(ids)) ;//(Arrays.asList(ids));
        return R.ok();
    }

    @ApiOperation("根据id删除报名人的")
    @PostMapping("/updateMark")
    public R updateMark(@RequestBody int id){
        CompetitionEntity competition = competionServer.getById(id);
        int mark = competition.getMark();
        competition.setMark(1-mark);
        boolean b = competionServer.updateById(competition);
        if(b) return  R.ok("修改成功");
        else return R.ok("修改失败");
    }

    @ApiOperation("展示全部比赛信息")
    @GetMapping("/list")
    public RR<Page> page( int page, int pageSize, String name){

        //log.finalize("page={},pageSize={},name={}",page,pageSize,name);

        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<CompetitionEntity> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        if(!(name.equals(""))) queryWrapper.eq(CompetitionEntity::getMark,1);
        //queryWrapper.eq(CompetitionEntity::getMark,1);
        //添加排序条件
        queryWrapper.orderByDesc(CompetitionEntity::getCreateTime);

        //执行查询
        competionServer.page(pageInfo,queryWrapper);

        return RR.success(pageInfo);
    }

    @ApiOperation("获取报名人的access_token")
    @GetMapping("/access_token")
    public String GetAccessToken () {
            SystemEntity system = systemService.lambdaQuery()
                    .eq(SystemEntity::getConfig, ConfigConstant.MINIAPP)
                    .one();
            if(system == null){
                throw new acmException("后台配置项不存在");
            }
            //小程序唯一标识   (在微信小程序管理后台获取)
            String appId = system.getValue();
            //小程序的 app secret (在微信小程序管理后台获取)
            String secret = system.getExtend();
            //向微信服务器 传入appid和secret，此步用来获取access_token
            String params = "grant_type=client_credential" + "&appid=" + appId + "&secret=" + secret ;
            //发送请求
            String sr = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
            //解析相应内容（转换成json对象）
            JSONObject json = JSON.parseObject(sr);
            //用户的唯一标识（openId）
            return (String) json.get("access_token");
    }

    @ApiOperation("获取报名人的OpenId")
    @GetMapping("/openid")
    public String GetOpenId (@RequestParam(value="code") String code) {

        SystemEntity system = systemService.lambdaQuery()
                .eq(SystemEntity::getConfig, ConfigConstant.MINIAPP)
                .one();
        if(system == null){
            throw new acmException("后台配置项不存在");
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
        String appId = system.getValue();
        //小程序的 app secret (在微信小程序管理后台获取)
        String secret = system.getExtend();
        //向微信服务器 传入appid和secret，此步用来获取access_token
        String params = "appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSON.parseObject(sr);
        //用户的唯一标识（openId）
        return (String) json.get("openid");
    }

}
